package com.luoshenshen.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.NettyRuntime;

/**
 * @author ShenshenLuo
 * @date 2025/3/22 20:30
 **/
public class NettyServer {

    public static void main(String[] args) {

        System.out.println("core size: " + NettyRuntime.availableProcessors());
        EventLoopGroup bossGroup = null;
        EventLoopGroup workerGroup = null;
        try {
            bossGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup(2);

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128) // 队列大小
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 长连接
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addFirst(new NettyServerHandler());
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });

            System.out.println("Starting server...");
            ChannelFuture sync = bootstrap.bind(8888).sync();

            ChannelConfig config = sync.channel().config();


            sync.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        System.out.println("server started listener done!");
                    }
                }
            });
            System.out.println("Server started on port 8888");
            sync.channel().closeFuture().sync();

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (bossGroup != null) {
                bossGroup.shutdownGracefully();
            }
            if (workerGroup != null) {
                workerGroup.shutdownGracefully();
            }
        }


    }
}
